import { Button, Descriptions, Modal, Select, Space, Table, Form, Input, message } from 'antd';
import React from 'react';

export default () => {
    const [db, setDb] = React.useState<IDBDatabase | null>();
    const [objectStores, setObjectStores] = React.useState<string[]>([]);
    const [tableData, setTableData] = React.useState<any[]>([]);
    const [selectedObjectStore, setSelectedObjectStores] = React.useState('');
    React.useEffect(() => {
        const request = window.indexedDB.open('why');
        request.onsuccess = function () {
            setDb(request.result);
            setObjectStores(Array.from(request.result.objectStoreNames));
        };
    }, []);
    const [form] = Form.useForm();
    function add() {
        if (!db) return;
        Modal.confirm({
            title: '新增数据',
            content: (
                <div>
                    <Form form={form}>
                        <Form.Item label="对象仓库名">{selectedObjectStore}</Form.Item>
                        <Form.Item label="id" name="id" required>
                            <Input />
                        </Form.Item>
                        <Form.Item label="name" name="name" required>
                            <Input />
                        </Form.Item>
                    </Form>
                </div>
            ),
            onOk() {
                return new Promise((resolve, reject) => {
                    console.log(form.getFieldsValue());
                    form.validateFields()
                        .then(() => {
                            const transaction = db.transaction([selectedObjectStore], 'readwrite');
                            const objectStore = transaction.objectStore(selectedObjectStore);
                            const request = objectStore.add(form.getFieldsValue());
                            request.onsuccess = function () {
                                form.resetFields();
                                resolve(true);
                                getData(selectedObjectStore);
                            };
                            request.onerror = function (e: any) {
                                reject(e);
                                message.error(e.target.error.message);
                            };
                        })
                        .catch(() => {
                            reject();
                        });
                });
            },
        });
    }

    function onSelect(value: any) {
        setSelectedObjectStores(value);
        getData(value);
    }

    function getData(value: any) {
        if (!db) return;
        const transaction = db.transaction([value]);
        const objectStore = transaction.objectStore(value);
        const request = objectStore.getAll();
        request.onsuccess = function (res: any) {
            console.log(res.target);
            setTableData(res.target.result);
        };
        request.onerror = function (e: any) {
            message.error(e.target.error.message);
        };
    }

    const columns = [
        {
            title: 'id',
            dataIndex: 'id',
        },
        {
            title: 'name',
            dataIndex: 'name',
        },
        {
            title: '操作',
            render: (row: any) => (
                <Space>
                    <Button onClick={() => onEditClick(row)}>修改</Button>
                    <Button onClick={() => onDeleteClick(row)}>删除</Button>
                </Space>
            ),
        },
    ];
    const onDeleteClick = (row: any) => {
        if (!db) return;
        const request = db
            .transaction([selectedObjectStore], 'readwrite')
            .objectStore(selectedObjectStore)
            .delete(row.id);
        request.onsuccess = function () {
            message.success('删除成功');
            getData(selectedObjectStore);
        };
        request.onerror = function (e: any) {
            message.error(e.target.error.message);
        };
    };

    const onEditClick = (row: any) => {
        form.setFieldsValue(row);
        if (!db) return;
        Modal.confirm({
            title: '修改数据',
            content: (
                <div>
                    <Form form={form}>
                        <Form.Item label="对象仓库名">{selectedObjectStore}</Form.Item>
                        <Form.Item label="id" name="id" required>
                            {row.id}
                        </Form.Item>
                        <Form.Item label="name" name="name" required>
                            <Input />
                        </Form.Item>
                    </Form>
                </div>
            ),
            onOk() {
                return new Promise((resolve, reject) => {
                    console.log(form.getFieldsValue());
                    form.validateFields()
                        .then(() => {
                            const transaction = db.transaction([selectedObjectStore], 'readwrite');
                            const objectStore = transaction.objectStore(selectedObjectStore);
                            const request = objectStore.put(form.getFieldsValue());
                            request.onsuccess = function () {
                                form.resetFields();
                                resolve(true);
                                getData(selectedObjectStore);
                            };
                            request.onerror = function (e: any) {
                                reject(e);
                                message.error(e.target.error.message);
                            };
                        })
                        .catch(() => {
                            reject();
                        });
                });
            },
        });
    };
    const onSearch = (value: string) => {
        if (!db) return
        if (value.trim() === '') {
            getData(selectedObjectStore)
            return
        }
        const index = db.transaction([selectedObjectStore], 'readwrite')
                        .objectStore(selectedObjectStore)
                        .index('name')
        const request = index.get(value)
        request.onsuccess = function (res: any) {
            console.log(res)
            setTableData([res.target.result] || [])
        }
    }
    return (
        <Space direction="vertical" style={{ width: '100%' }}>
            <Descriptions
                title="数据库信息"
                extra={
                    <Space>
                        <Button onClick={add} disabled={!selectedObjectStore}>
                            新增数据
                        </Button>
                    </Space>
                }
                bordered
            >
                <Descriptions.Item label="数据库名">{db?.name}</Descriptions.Item>
                <Descriptions.Item label="数据库版本">{db?.version}</Descriptions.Item>
            </Descriptions>
            <Space>
                <Select style={{ width: 200 }} onSelect={onSelect}>
                    {objectStores.map((storeName) => (
                        <Select.Option value={storeName} key={storeName}>
                            {storeName}
                        </Select.Option>
                    ))}
                </Select>
                <Input.Search disabled={!selectedObjectStore} style={{ width: 300 }}  onSearch={onSearch}/>
            </Space>
            <Table dataSource={tableData} columns={columns} rowKey="id" />
        </Space>
    );
};
